import { Request, Response } from 'express';
import { DatabaseConnection } from '@/database/connection';
import { LLMServiceFactory } from '@/services/LLMService';
import { Logger } from '@/utils/logger';
import { 
  ValidationError, 
  NotFoundError,
  asyncHandler 
} from '@/middleware/errorHandler';
import { AnalysisRequest } from '@/types/models';

interface AuthenticatedRequest extends Request {
  user: {
    id: string;
    username: string;
    [key: string]: any;
  };
}

const logger = new Logger('AIAnalysisController');

export class AIAnalysisController {
  /**
   * 请求AI健康分析
   */
  public requestAnalysis = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
    const { user } = req;
    const analysisRequest: AnalysisRequest = req.body;
    const db = DatabaseConnection.getConnection();

    // 获取用户的LLM配置
    const llmConfig = await db('llm_configurations')
      .where('user_id', user.id)
      .where('is_active', true)
      .first();

    if (!llmConfig) {
      throw new ValidationError('请先配置AI服务提供商');
    }

    // 解密API密钥（这里简化处理，实际应该使用加密存储）
    const decryptedApiKey = this.decryptApiKey(llmConfig.api_key_encrypted);

    const llmServiceConfig = {
      provider: llmConfig.provider,
      apiKey: decryptedApiKey,
      endpoint: llmConfig.endpoint_url,
      model: llmConfig.model_config?.model,
      temperature: llmConfig.model_config?.temperature,
      maxTokens: llmConfig.model_config?.maxTokens
    };

    const startTime = Date.now();

    try {
      // 收集健康数据
      const healthData = await this.collectHealthData(
        user.id, 
        analysisRequest.analysis_type,
        analysisRequest.date_range
      );

      // 获取用户资料
      const userProfile = await this.getUserProfile(user.id);

      // 创建LLM服务实例
      const llmService = LLMServiceFactory.createService(llmServiceConfig);

      // 创建分析提示词
      const messages = llmService['createHealthAnalysisPrompt'](
        healthData, 
        analysisRequest.analysis_type,
        userProfile
      );

      // 发送到LLM进行分析
      const llmResponse = await llmService.sendMessage(messages);
      
      // 解析分析结果
      const analysisResult = llmService['parseAnalysisResult'](llmResponse.content);
      const validatedResult = llmService['validateAnalysisResult'](analysisResult);

      const processingTime = Date.now() - startTime;

      // 保存分析结果
      const savedResult = await db('analysis_results').insert({
        user_id: user.id,
        analysis_type: analysisRequest.analysis_type,
        analysis_date: new Date(analysisRequest.date_range.end_date),
        input_data: JSON.stringify(healthData),
        analysis_content: validatedResult.analysis,
        recommendations: JSON.stringify(validatedResult.recommendations),
        health_score: validatedResult.score,
        metrics: JSON.stringify({
          confidence: 0.85, // 这里可以添加更多指标
          complexity: 'medium'
        }),
        llm_provider: llmConfig.provider,
        model_version: llmServiceConfig.model || 'default',
        processing_time_ms: processingTime,
        status: 'completed',
        created_at: new Date(),
        updated_at: new Date()
      }).returning(['id']);

      logger.info('AI analysis completed successfully', {
        userId: user.id,
        analysisType: analysisRequest.analysis_type,
        processingTime,
        provider: llmConfig.provider,
        resultId: savedResult[0]?.id
      });

      res.json({
        success: true,
        data: {
          id: savedResult[0]?.id,
          analysisType: analysisRequest.analysis_type,
          analysis: validatedResult.analysis,
          recommendations: validatedResult.recommendations,
          healthScore: validatedResult.score,
          processingTime,
          provider: llmConfig.provider,
          createdAt: new Date().toISOString()
        },
        message: 'AI分析完成'
      });

    } catch (error) {
      const processingTime = Date.now() - startTime;

      // 保存失败记录
      await db('analysis_results').insert({
        user_id: user.id,
        analysis_type: analysisRequest.analysis_type,
        analysis_date: new Date(analysisRequest.date_range.end_date),
        input_data: JSON.stringify({}),
        analysis_content: '',
        llm_provider: llmConfig.provider,
        processing_time_ms: processingTime,
        status: 'failed',
        error_message: error.message,
        created_at: new Date(),
        updated_at: new Date()
      }).catch(saveError => {
        logger.error('Failed to save error analysis result', { 
          saveError: saveError.message 
        });
      });

      logger.error('AI analysis failed', {
        userId: user.id,
        analysisType: analysisRequest.analysis_type,
        processingTime,
        error: error.message
      });

      throw error;
    }
  });

  /**
   * 获取分析结果列表
   */
  public getAnalysisResults = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
    const { user } = req;
    const { type, limit = 10, offset = 0 } = req.query;
    const db = DatabaseConnection.getConnection();

    let query = db('analysis_results')
      .where('user_id', user.id)
      .where('status', 'completed');

    if (type) {
      query = query.where('analysis_type', type as string);
    }

    const results = await query
      .orderBy('created_at', 'desc')
      .limit(parseInt(limit as string))
      .offset(parseInt(offset as string));

    const totalCount = await db('analysis_results')
      .where('user_id', user.id)
      .where('status', 'completed')
      .modify(qb => {
        if (type) qb.where('analysis_type', type as string);
      })
      .count('* as count')
      .first();

    const responseData = results.map(result => ({
      id: result.id,
      analysisType: result.analysis_type,
      analysisDate: result.analysis_date,
      analysis: result.analysis_content,
      recommendations: result.recommendations ? JSON.parse(result.recommendations) : [],
      healthScore: result.health_score,
      provider: result.llm_provider,
      processingTime: result.processing_time_ms,
      createdAt: result.created_at
    }));

    res.json({
      success: true,
      data: responseData,
      pagination: {
        total: totalCount?.count || 0,
        limit: parseInt(limit as string),
        offset: parseInt(offset as string)
      }
    });
  });

  /**
   * 获取单个分析结果详情
   */
  public getAnalysisResult = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
    const { user } = req;
    const { resultId } = req.params;
    const db = DatabaseConnection.getConnection();

    const result = await db('analysis_results')
      .where('id', resultId)
      .where('user_id', user.id)
      .first();

    if (!result) {
      throw new NotFoundError('分析结果不存在');
    }

    const responseData = {
      id: result.id,
      analysisType: result.analysis_type,
      analysisDate: result.analysis_date,
      analysis: result.analysis_content,
      recommendations: result.recommendations ? JSON.parse(result.recommendations) : [],
      healthScore: result.health_score,
      metrics: result.metrics ? JSON.parse(result.metrics) : {},
      inputData: result.input_data ? JSON.parse(result.input_data) : {},
      provider: result.llm_provider,
      modelVersion: result.model_version,
      processingTime: result.processing_time_ms,
      status: result.status,
      createdAt: result.created_at
    };

    res.json({
      success: true,
      data: responseData
    });
  });

  /**
   * 测试LLM连接
   */
  public testLLMConnection = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
    const { provider, apiKey, endpoint } = req.body;

    if (!provider || !apiKey) {
      throw new ValidationError('提供商和API密钥是必需的');
    }

    const llmServiceConfig = {
      provider,
      apiKey,
      endpoint: endpoint || undefined
    };

    try {
      const llmService = LLMServiceFactory.createService(llmServiceConfig);
      const testResult = await llmService.testConnection();

      logger.info('LLM connection test completed', {
        provider,
        success: testResult.success,
        responseTime: testResult.responseTime
      });

      res.json({
        success: true,
        data: testResult,
        message: testResult.success ? '连接测试成功' : '连接测试失败'
      });

    } catch (error) {
      logger.error('LLM connection test failed', {
        provider,
        error: error.message
      });

      res.json({
        success: false,
        data: {
          success: false,
          message: `连接测试失败: ${error.message}`
        },
        message: '连接测试失败'
      });
    }
  });

  /**
   * 获取AI分析统计
   */
  public getAnalysisStats = asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
    const { user } = req;
    const db = DatabaseConnection.getConnection();

    // 获取分析统计
    const stats = await db('analysis_results')
      .where('user_id', user.id)
      .where('status', 'completed')
      .select(
        db.raw('analysis_type'),
        db.raw('COUNT(*) as count'),
        db.raw('AVG(health_score) as avg_score'),
        db.raw('AVG(processing_time_ms) as avg_processing_time')
      )
      .groupBy('analysis_type');

    // 获取最近的分析
    const recentAnalysis = await db('analysis_results')
      .where('user_id', user.id)
      .where('status', 'completed')
      .orderBy('created_at', 'desc')
      .limit(5)
      .select('id', 'analysis_type', 'health_score', 'created_at');

    // 获取健康得分趋势
    const scoreTrends = await db('analysis_results')
      .where('user_id', user.id)
      .where('status', 'completed')
      .where('created_at', '>=', db.raw('DATE("now", "-30 days")'))
      .orderBy('created_at', 'asc')
      .select('analysis_date', 'analysis_type', 'health_score', 'created_at');

    res.json({
      success: true,
      data: {
        stats: stats.map(stat => ({
          type: stat.analysis_type,
          count: stat.count,
          averageScore: Math.round(stat.avg_score || 0),
          averageProcessingTime: Math.round(stat.avg_processing_time || 0)
        })),
        recentAnalysis: recentAnalysis.map(analysis => ({
          id: analysis.id,
          type: analysis.analysis_type,
          score: analysis.health_score,
          date: analysis.created_at
        })),
        scoreTrends
      }
    });
  });

  /**
   * 收集健康数据
   */
  private async collectHealthData(
    userId: string, 
    analysisType: string, 
    dateRange: { start_date: string; end_date: string }
  ): Promise<any> {
    const db = DatabaseConnection.getConnection();
    const healthData: any = {};

    // 获取日常健康数据
    const dailyData = await db('health_data')
      .where('user_id', userId)
      .whereBetween('record_date', [dateRange.start_date, dateRange.end_date])
      .orderBy('record_date', 'desc')
      .first();

    if (dailyData) {
      healthData.dailyData = {
        date: dailyData.record_date,
        steps: dailyData.steps,
        distance: dailyData.distance,
        calories: dailyData.calories,
        activeMinutes: dailyData.active_minutes,
        averageHeartRate: dailyData.avg_heart_rate,
        maxHeartRate: dailyData.max_heart_rate,
        minHeartRate: dailyData.min_heart_rate,
        stressLevel: dailyData.stress_level
      };
    }

    // 获取睡眠数据（特别是睡眠分析类型）
    if (analysisType === 'sleep' || analysisType === 'general') {
      const sleepData = await db('sleep_data')
        .where('user_id', userId)
        .whereBetween('sleep_date', [dateRange.start_date, dateRange.end_date])
        .orderBy('sleep_date', 'desc')
        .first();

      if (sleepData) {
        healthData.sleepData = {
          sleepDate: sleepData.sleep_date,
          bedtime: sleepData.bedtime,
          sleepStart: sleepData.sleep_start,
          wakeTime: sleepData.wake_time,
          totalDuration: sleepData.total_duration,
          deepSleep: sleepData.deep_sleep,
          lightSleep: sleepData.light_sleep,
          remSleep: sleepData.rem_sleep,
          awakeDuration: sleepData.awake_duration,
          sleepEfficiency: sleepData.sleep_efficiency,
          sleepScore: sleepData.sleep_score,
          wakeUpCount: sleepData.wake_up_count
        };
      }
    }

    // 获取趋势数据（用于综合分析）
    if (analysisType === 'general') {
      const trendData = await db('health_data')
        .where('user_id', userId)
        .where('record_date', '>=', db.raw('DATE("now", "-30 days")'))
        .orderBy('record_date', 'asc');

      if (trendData.length > 0) {
        healthData.trends = {
          steps: this.calculateTrend(trendData.map(d => d.steps)),
          calories: this.calculateTrend(trendData.map(d => d.calories)),
          heartRate: this.calculateTrend(trendData.map(d => d.avg_heart_rate).filter(Boolean))
        };
      }
    }

    return healthData;
  }

  /**
   * 获取用户资料
   */
  private async getUserProfile(userId: string): Promise<any> {
    const db = DatabaseConnection.getConnection();

    const profile = await db('user_profiles')
      .where('user_id', userId)
      .first();

    if (!profile) {
      return null;
    }

    // 计算年龄
    let age = null;
    if (profile.birth_date) {
      const birthDate = new Date(profile.birth_date);
      const today = new Date();
      age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
    }

    return {
      age,
      gender: profile.gender,
      height: profile.height,
      weight: profile.weight
    };
  }

  /**
   * 计算趋势
   */
  private calculateTrend(values: number[]): { trend: string; change: number } {
    if (values.length < 2) {
      return { trend: 'stable', change: 0 };
    }

    const firstHalf = values.slice(0, Math.floor(values.length / 2));
    const secondHalf = values.slice(Math.floor(values.length / 2));

    const firstAvg = firstHalf.reduce((sum, val) => sum + val, 0) / firstHalf.length;
    const secondAvg = secondHalf.reduce((sum, val) => sum + val, 0) / secondHalf.length;

    const change = ((secondAvg - firstAvg) / firstAvg) * 100;

    let trend = 'stable';
    if (Math.abs(change) > 5) {
      trend = change > 0 ? 'increasing' : 'decreasing';
    }

    return {
      trend,
      change: Math.round(change * 100) / 100
    };
  }

  /**
   * 解密API密钥（简化实现，实际应该使用专门的加密库）
   */
  private decryptApiKey(encryptedKey: string): string {
    // 这里应该实现真正的解密逻辑
    // 目前简化为base64解码
    try {
      return Buffer.from(encryptedKey, 'base64').toString('utf8');
    } catch (error) {
      logger.error('Failed to decrypt API key', { error: error.message });
      return encryptedKey; // 如果解密失败，返回原始值
    }
  }
}